import { Request } from 'express'
import path from 'path'
import multer from 'multer'
import { mkdirCheckExists, getSuffix, parseTime } from '../utils'

// 保存文件设置
const SaveFileConfig = multer({
  storage: multer.diskStorage({
    // 生成保存路径
    destination: function(req, file, cb) {
      mkdirCheckExists(UploadMidware.RESOURCES_PATH)
      cb(null, UploadMidware.RESOURCES_PATH)
    },
    filename: function(req, file, cb) {
      const suffix = getSuffix(file.originalname)
      const now = new Date()
      const fileName = parseTime(now, `{y}{m}{d}{h}{i}{s}_${now.getMilliseconds()}`) + `.${suffix}`

      if (!req[UploadMidware.UPLOAD_FILEPATH_KEY]) req[UploadMidware.UPLOAD_FILEPATH_KEY] = []
      if (!req[UploadMidware.UPLOAD_FILENAME_KEY]) req[UploadMidware.UPLOAD_FILENAME_KEY] = []

      req[UploadMidware.UPLOAD_FILEPATH_KEY].push(path.join(UploadMidware.RESOURCES_PATH, fileName))
      req[UploadMidware.UPLOAD_FILENAME_KEY].push(fileName)

      cb(null, fileName)
    },
  }),
})

/**
 * 上传文件中间件
*/
export default class UploadMidware {
  static readonly RESOURCES_PATH = global.Config.RESOURCES_PATH

  static readonly UPLOAD_FILEPATH_KEY = 'UPLOAD_FILEPATH_KEY'

  static readonly UPLOAD_FILENAME_KEY = 'UPLOAD_FILENAME_KEY'

  /**
   * 单个文件上传
  */
  static single = (fieldName: string) => SaveFileConfig.single(fieldName)

  /**
   * 获取单个文件路径
  */
  static getSingleFilePath = (req: Request) => {
    const filePath = req[UploadMidware.UPLOAD_FILEPATH_KEY] as string[]
    return filePath[0] || ''
  }

  /**
   * 获取单个文件名称
  */
  static getSingleFileName = (req: Request) => {
    const fileName = req[UploadMidware.UPLOAD_FILENAME_KEY] as string[]
    return fileName[0] || ''
  }

  /**
   * 多个文件上传
  */
  static multiple = (fields: readonly multer.Field[]) => SaveFileConfig.fields(fields)

  /**
   * 获取多个文件路径
  */
  static getMultipleFilePath = (req: Request) => {
    return (req[UploadMidware.UPLOAD_FILEPATH_KEY] || []) as string[]
  }

  /**
   * 获取多个文件名称
  */
  static getMultipleFileName = (req: Request) => {
    return (req[UploadMidware.UPLOAD_FILENAME_KEY] || []) as string[]
  }
}